package com.starhub.engine.generator.genid;

import com.starhub.common.exception.AppException;
import com.starhub.utils.Util;

/**
 * 雪花算法ID生成器
 */
public class IdGenerator {
    // 起始时间戳（2023-01-01 00:00:00）
    private static final long EPOCH = 1672531200000L;

    // 各部分位数配置
    private static final long SEQUENCE_BITS = 12L;
    private static final long WORKER_ID_BITS = 5L;
    private static final long DATACENTER_ID_BITS = 5L;

    // 最大值计算
    private static final long MAX_SEQUENCE = ~(-1L << SEQUENCE_BITS);
    private static final long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS);
    private static final long MAX_DATACENTER_ID = ~(-1L << DATACENTER_ID_BITS);

    // 左移位数
    private static final long WORKER_ID_SHIFT = SEQUENCE_BITS;
    private static final long DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
    private static final long TIMESTAMP_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS;

    private final long workerId;
    private final long datacenterId;
    private long sequence = 0L;
    private long lastTimestamp = -1L;

    /**
     * 构造函数
     * @param workerId 工作节点ID (0-31)
     * @param datacenterId 数据中心ID (0-31)
     */
    public IdGenerator(long workerId, long datacenterId) {
        if (workerId > MAX_WORKER_ID || workerId < 0) {
            throw new IllegalArgumentException("Worker ID超出范围");
        }
        if (datacenterId > MAX_DATACENTER_ID || datacenterId < 0) {
            throw new IllegalArgumentException("Datacenter ID超出范围");
        }
        this.workerId = workerId;
        this.datacenterId = datacenterId;
    }

    /**
     * 生成下一个ID
     */
    public synchronized long generate() {
        long timestamp = timeGen();

        // 处理时钟回拨
        if (timestamp < lastTimestamp) {
            handleClockBackwards(timestamp);
            timestamp = timeGen(); // 重新获取时间
        }

        // 同一毫秒内生成
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & MAX_SEQUENCE;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = timestamp;

        return ((timestamp - EPOCH) << TIMESTAMP_SHIFT)
                | (datacenterId << DATACENTER_ID_SHIFT)
                | (workerId << WORKER_ID_SHIFT)
                | sequence;
    }

    /**
     * 阻塞到下一毫秒
     */
    private long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    /**
     * 处理时钟回拨
     */
    private void handleClockBackwards(long timestamp) {
        long offset = lastTimestamp - timestamp;
        if (offset <= 5) { // 允许5ms内的回拨
            try {
                Thread.sleep(offset);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new AppException("时钟回拨等待中断");
            }
        } else {
            throw new AppException("时钟回拨过大，拒绝生成ID");
        }
    }

    /**
     * 获取当前时间戳
     */
    protected long timeGen() {
        return System.currentTimeMillis();
    }


    /**
     * 雪花算法ID生成器
     * @return id
     */
    public static long generateId() {
        IdGenerator idGenerator = new IdGenerator(1, 1);
        return idGenerator.generate();
    }

    /**
     * 雪花算法ID生成器
     * @return id
     */
    public static String generateIdStr() {
        return Util.null2String(generateId());
    }
}